import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:qunaimedical/components/custom_divider.dart';
import 'package:qunaimedical/components/item_check_item.dart';
import 'package:qunaimedical/models/check_item.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/patient.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/patient_manage/check_item_create.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/constants.dart';
import 'package:qunaimedical/values/urls.dart';

/// 检查项列表
class CheckItemListPage extends StatefulWidget {
  final Patient item;

  const CheckItemListPage(
    this.item, {
    Key key,
  }) : super(key: key);

  @override
  _CheckItemListPageState createState() => _CheckItemListPageState();
}

class _CheckItemListPageState extends State<CheckItemListPage> {
  // 是否有下一页
  int _nextPage = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  List<CheckItem> _items = [];

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('健康检查列表'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (c) => CheckItemCreatePage(widget.item),
                ),
              ).then((value) {
                if (value != null && value) {
                  _fetchData();
                }
              });
            },
            child: Text(
              '添加检查项',
              style: TextStyle(color: Theme.of(context).primaryColor),
            ),
          ),
        ],
      ),
      body: SmartRefresher(
        controller: _refreshController,
        enablePullUp: _nextPage != 1,
        onRefresh: _fetchData,
        onLoading: _loadMore,
        child: ListView.separated(
          padding: EdgeInsets.only(
            top: 10,
            bottom: 50,
          ),
          itemBuilder: (c, i) => ItemHealthCheck(
            item: _items[i],
            onDelete: () => _delete(i),
          ),
          itemCount: _items.length,
          separatorBuilder: (c, i) => CustomDivider(),
        ),
      ),
    );
  }

  void _delete(int index) async {
    DialogUtils.showAlertDialog(context, '提示', '确认删除？', onPressed: () async {
      Navigator.pop(context);
      DialogUtils.showWaitDialog(context);
      var data = await XHttp.postJson(
          Urls.CHECK_ITEM_DELETE, {"id": _items[index].id});
      Navigator.pop(context);
      if (data != null) {
        Map<String, dynamic> response = data as Map<String, dynamic>;
        if (response['code'] == 1) {
          setState(() {
            _items.removeAt(index);
          });
        }
      }
    });
  }

  void _fetchData() async {
    var data = await XHttp.postJson(Urls.CHECK_ITEM_LIST, {
      "pageSize": Constants.limit,
      "pageNo": 1,
      "patientAccount": widget.item.patiAccountId //患者账号id
    });
    _refreshController.refreshCompleted();
    if (data != null) {
      var response = MapResponse.fromJson(data);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => CheckItem.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items = records;
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  void _loadMore() async {
    var result = await XHttp.postJson(Urls.CHECK_ITEM_LIST, {
      "pageSize": Constants.limit,
      "pageNo": _nextPage,
      "patientAccount": widget.item.patiAccountId //患者账号id
    });
    _refreshController.loadComplete();
    if (result != null) {
      var response = MapResponse.fromJson(result);
      if (response.code == 1) {
        if (response.data['pages'] == response.data['current']) {
          _nextPage = 1;
        } else {
          _nextPage = response.data['pages'] + 1;
        }
        var records = (response.data['records'] as List)
            .map((e) => CheckItem.fromJson((e as Map<String, dynamic>)))
            .toList();
        if (mounted) {
          setState(() {
            _items.addAll(records);
          });
        }
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }
}
